<template>
  <div class="user-list">
    <div class="user-header">
      <h2>用户列表</h2>
      <el-button type="primary" @click="openDialog('add')">新增用户</el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索用户名"
        @input="searchUsers"
        class="search-input"
      />
    </div>
    <el-table :data="filteredUsers" border style="margin-top: 20px">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="role" label="角色" />
      <el-table-column prop="active" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.active ? 'success' : 'danger'">
            {{ row.active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="openDialog('edit', row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(row.id)">删除</el-button>
          <el-switch
            v-model="row.active"
            active-text="启用"
            inactive-text="禁用"
            @change="toggleUserStatus(row.id)"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredUsers.length"
    />

    <el-dialog v-model="dialogVisible" :title="isEditing ? '编辑用户' : '新增用户'">
      <el-form :model="currentUser" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentUser.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentUser.email" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="currentUser.role" placeholder="请选择角色">
            <el-option label="管理员" value="管理员" />
            <el-option label="普通用户" value="普通用户" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="active">
          <el-switch v-model="currentUser.active" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useUserStore } from '@/stores/userStore';
import { ElMessage } from 'element-plus';

const userStore = useUserStore();
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const dialogVisible = ref(false);
const isEditing = ref(false);
const currentUser = ref({
  id: null,
  username: '',
  email: '',
  role: '',
  active: true
});
const formRef = ref(null);

const filteredUsers = computed(() => {
  return userStore.users.filter(user =>
    user.username.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
};

const openDialog = (type, user = null) => {
  isEditing.value = type === 'edit';
  currentUser.value = isEditing.value ? { ...user } : { id: null, username: '', email: '', role: '', active: true };
  dialogVisible.value = true;
};

const deleteUser = (id) => {
  userStore.deleteUser(id);
  ElMessage.success('删除用户成功');
};

const toggleUserStatus = (id) => {
  userStore.toggleUserStatus(id);
  ElMessage.success('用户状态更新成功');
};

const saveUser = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    if (isEditing.value) {
      userStore.updateUser(currentUser.value);
      ElMessage.success('编辑用户成功');
    } else {
      userStore.addUser({ ...currentUser.value });
      ElMessage.success('新增用户成功');
    }
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error('保存失败，请检查表单信息');
  }
};

const searchUsers = () => {
  currentPage.value = 1;
};

const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};
</script>

<style scoped>
.user-list {
  padding: 20px;
}
.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.search-input {
  width: 200px;
}
</style>
